﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ClearingRestartingAutomaton.Common
{
    /// <summary>
    /// Static class encapsulating helper extension methods for strings.
    /// </summary>
    public static class StringExtensionMethods
    {
        /// <summary>
        /// Returns the longest possible prefix of this word of length at most K.
        /// </summary>
        /// <param name="word">This word.</param>
        /// <param name="K">The length of the prefix.</param>
        /// <returns>String representing the longest possible prefix of this word of length at most K.</returns>
        public static string FirstK(this string word, int K)
        {
            if (K < 0) throw new ArgumentException("K must be nonnegative.");
            if (String.IsNullOrEmpty(word)) return String.Empty;
            if (word.Length <= K) return word;
            else return word.Substring(0, K);
        }

        /// <summary>
        /// Returns the longest possible suffix of this word of length at most K.
        /// </summary>
        /// <param name="word">This word.</param>
        /// <param name="K">The length of the suffix.</param>
        /// <returns>String representing the longest possible suffix of this word of length at most K.</returns>
        public static string LastK(this string word, int K)
        {
            if (K < 0) throw new ArgumentException("K must be nonnegative.");
            if (String.IsNullOrEmpty(word)) return String.Empty;
            if (word.Length <= K) return word;
            else return word.Substring(word.Length - K);
        }

        /// <summary>
        /// Compares two strings based on length-lexicographical and indicates whether 
        /// the left hand side string precedes, follows, or appears in the same position 
        /// in the sort order as the right hand side string.
        /// </summary>
        /// <param name="lhs">Left hand side string.</param>
        /// <param name="rhs">Right hand side string.</param>
        /// <returns>
        /// A 32-bit signed integer that indicates whether the left hand side string precedes, follows, 
        /// or appears in the same position in the length-lexicographical order as the right hand side string.
        /// Value Condition Less than zero: the left hand side string precedes the right hand side string. 
        /// Zero: the left hand side string has the same position in the sort order as the right hand side string. 
        /// Greater than zero: the left hand side string follows the right hand side string.
        /// </returns>
        public static int LengthLexCompare(this string lhs, string rhs)
        {
            if (lhs.Length < rhs.Length) return -1;
            if (lhs.Length > rhs.Length) return +1;
            return lhs.CompareTo(rhs);
        }
    }
}
